<script setup lang="ts">
import type { GovernanceProposal } from '../../../types/zhu-family';

import { computed, ref } from 'vue';

import { PlusOutlined, UserOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

import { governanceProposals } from '../../../mock/zhu-dynasty/governance';
import { kingdoms } from '../../../mock/zhu-dynasty/members';

const activeTab = ref('proposals');
const proposalModalVisible = ref(false);
const showCreateProposal = ref(false);
const selectedProposal = ref<GovernanceProposal | null>(null);
const proposals = ref(governanceProposals);

const newProposal = ref({
  title: '',
  type: 'law',
  description: '',
});

const voterColumns = [
  { title: '成员', dataIndex: 'memberName', key: 'memberName' },
  { title: '藩国', dataIndex: 'memberKingdom', key: 'memberKingdom' },
  { title: '投票', key: 'vote' },
  { title: '权重', dataIndex: 'weight', key: 'weight' },
  { title: '投票时间', dataIndex: 'voteTime', key: 'voteTime' },
];

const voteRecordColumns = [
  { title: '成员', dataIndex: 'memberName', key: 'memberName' },
  { title: '藩国', dataIndex: 'memberKingdom', key: 'memberKingdom' },
  { title: '投票', key: 'vote' },
  { title: '权重', dataIndex: 'weight', key: 'weight' },
];

const allVoters = computed(() => {
  return proposals.value.flatMap((p) => p.voters);
});

function getProposalTypeIcon(type: string) {
  const icons: Record<string, string> = {
    law: '律',
    finance: '财',
    military: '军',
    ceremony: '礼',
  };
  return icons[type] || '提';
}

function getProposalTypeText(type: string) {
  const texts: Record<string, string> = {
    law: '法律',
    finance: '财政',
    military: '军事',
    ceremony: '礼仪',
  };
  return texts[type] || type;
}

function getStatusColor(status: string) {
  const colors: Record<string, string> = {
    voting: 'processing',
    passed: 'success',
    rejected: 'error',
    executed: 'default',
  };
  return colors[status] || 'default';
}

function getStatusText(status: string) {
  const texts: Record<string, string> = {
    voting: '投票中',
    passed: '已通过',
    rejected: '已否决',
    executed: '已执行',
  };
  return texts[status] || status;
}

function getKingdomName(kingdomId: string) {
  const kingdom = kingdoms.find((k) => k.id === kingdomId);
  return kingdom?.name || '未知';
}

function formatTime(time: string) {
  return dayjs(time).format('YYYY年MM月DD日 HH:mm');
}

function viewProposal(proposal: GovernanceProposal) {
  selectedProposal.value = proposal;
  proposalModalVisible.value = true;
}

function voteProposal(proposal: GovernanceProposal, vote: 'against' | 'for') {
  message.success(
    `您已对提案"${proposal.title}"投${vote === 'for' ? '赞成' : '反对'}票（Mock模式）`,
  );
}

function handleCreateProposal() {
  message.success('提案创建成功！（Mock模式）');
  showCreateProposal.value = false;
  newProposal.value = { title: '', type: 'law', description: '' };
}
</script>

<template>
  <div class="governance-page">
    <a-card title="⚖️ 朝政治理中心">
      <a-tabs v-model:active-key="activeTab">
        <a-tab-pane key="proposals" tab="提案投票">
          <a-space
            direction="vertical"
            style="width: 100%; margin-bottom: 16px"
          >
            <a-button type="primary" @click="showCreateProposal = true">
              <PlusOutlined /> 发起新提案
            </a-button>
          </a-space>

          <a-list :data-source="proposals" :pagination="{ pageSize: 5 }">
            <template #renderItem="{ item }">
              <a-list-item>
                <a-list-item-meta :description="item.description">
                  <template #avatar>
                    <a-avatar style="background-color: #1890ff">
                      {{ getProposalTypeIcon(item.type) }}
                    </a-avatar>
                  </template>
                  <template #title>
                    <div class="proposal-title">
                      <span>{{ item.title }}</span>
                      <a-tag :color="getStatusColor(item.status)">
                        {{ getStatusText(item.status) }}
                      </a-tag>
                    </div>
                  </template>
                </a-list-item-meta>
                <div class="proposal-info">
                  <div class="proposer">
                    <UserOutlined />
                    {{ item.proposer }} ({{
                      getKingdomName(item.proposerKingdom)
                    }})
                  </div>
                  <div class="vote-progress">
                    <a-progress
                      :percent="
                        Math.round((item.votesFor / item.votesRequired) * 100)
                      "
                      :status="item.status === 'passed' ? 'success' : 'active'"
                    />
                    <div class="vote-count">
                      赞成: {{ item.votesFor }} / 反对:
                      {{ item.votesAgainst }} (需要: {{ item.votesRequired }})
                    </div>
                  </div>
                  <a-space>
                    <a-button
                      type="primary"
                      size="small"
                      @click="viewProposal(item)"
                    >
                      查看详情
                    </a-button>
                    <a-button
                      v-if="item.status === 'voting'"
                      size="small"
                      @click="voteProposal(item, 'for')"
                    >
                      投票
                    </a-button>
                  </a-space>
                </div>
              </a-list-item>
            </template>
          </a-list>
        </a-tab-pane>

        <a-tab-pane key="voters" tab="投票记录">
          <a-table
            :columns="voterColumns"
            :data-source="allVoters"
            size="small"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'vote'">
                <a-tag :color="record.vote === 'for' ? 'green' : 'red'">
                  {{ record.vote === 'for' ? '赞成' : '反对' }}
                </a-tag>
              </template>
            </template>
          </a-table>
        </a-tab-pane>

        <a-tab-pane key="rules" tab="治理规则">
          <a-descriptions bordered :column="2">
            <a-descriptions-item label="投票权重规则">
              皇帝: 3票, 藩王: 2票, 其他宗室: 1票
            </a-descriptions-item>
            <a-descriptions-item label="提案通过阈值">
              总票数 ≥ 10票，且赞成票 > 反对票
            </a-descriptions-item>
            <a-descriptions-item label="提案类型">
              法律、财政、军事、礼仪
            </a-descriptions-item>
            <a-descriptions-item label="投票期限">
              自提案发起后 30 天内
            </a-descriptions-item>
          </a-descriptions>
        </a-tab-pane>
      </a-tabs>
    </a-card>

    <!-- 提案详情Modal -->
    <a-modal
      v-model:open="proposalModalVisible"
      title="提案详情"
      width="700px"
      @ok="proposalModalVisible = false"
    >
      <div v-if="selectedProposal" class="proposal-detail">
        <h3>{{ selectedProposal.title }}</h3>
        <a-descriptions
          :column="1"
          bordered
          size="small"
          style="margin: 16px 0"
        >
          <a-descriptions-item label="提案人">
            {{ selectedProposal.proposer }}
          </a-descriptions-item>
          <a-descriptions-item label="藩国">
            {{ getKingdomName(selectedProposal.proposerKingdom) }}
          </a-descriptions-item>
          <a-descriptions-item label="提案类型">
            {{ getProposalTypeText(selectedProposal.type) }}
          </a-descriptions-item>
          <a-descriptions-item label="发起时间">
            {{ formatTime(selectedProposal.createTime) }}
          </a-descriptions-item>
          <a-descriptions-item label="截止时间">
            {{ formatTime(selectedProposal.voteEndTime) }}
          </a-descriptions-item>
        </a-descriptions>

        <h4>提案内容</h4>
        <p>{{ selectedProposal.description }}</p>

        <h4 style="margin-top: 16px">投票情况</h4>
        <a-table
          :columns="voteRecordColumns"
          :data-source="selectedProposal.voters"
          :pagination="false"
          size="small"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'vote'">
              <a-tag :color="record.vote === 'for' ? 'green' : 'red'">
                {{ record.vote === 'for' ? '赞成' : '反对' }}
              </a-tag>
            </template>
          </template>
        </a-table>
      </div>
    </a-modal>

    <!-- 创建提案Modal -->
    <a-modal
      v-model:open="showCreateProposal"
      title="发起新提案"
      @ok="handleCreateProposal"
    >
      <a-form :model="newProposal" layout="vertical">
        <a-form-item label="提案标题">
          <a-input
            v-model:value="newProposal.title"
            placeholder="输入提案标题"
          />
        </a-form-item>
        <a-form-item label="提案类型">
          <a-select v-model:value="newProposal.type">
            <a-select-option value="law">法律</a-select-option>
            <a-select-option value="finance">财政</a-select-option>
            <a-select-option value="military">军事</a-select-option>
            <a-select-option value="ceremony">礼仪</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="提案内容">
          <a-textarea
            v-model:value="newProposal.description"
            :rows="4"
            placeholder="详细描述提案内容"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped lang="scss">
.governance-page {
  .proposal-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .proposal-info {
    display: flex;
    flex-direction: column;
    gap: 8px;
    min-width: 300px;

    .proposer {
      font-size: 12px;
      color: #666;
    }

    .vote-progress {
      .vote-count {
        margin-top: 4px;
        font-size: 12px;
        color: #666;
      }
    }
  }

  .proposal-detail {
    h3 {
      margin-bottom: 16px;
    }

    h4 {
      margin: 16px 0 8px;
    }

    p {
      line-height: 1.6;
      color: #666;
    }
  }
}
</style>
